<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/8/3
 * Time: 10:52
 */
class BatchDeliveryAction extends Action{
    //批量发货列表
    public function batchList($deliveryNumber=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $batchModel = M("module_order_batch_delivery");
        Session::switchCustomer($customerId);
        $condition['deleted']=array("eq",0);
        $condition['cId']=array("eq",$customerId);
        $deliveryNumber?$condition['deliveryNumber']=array("like","%$deliveryNumber%"):"";
        $arr = $batchModel->where($condition)->order("updateTime desc")->limit($start,$limit)->select();
        if($arr){
            $count = $batchModel->where($condition)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //删除批量发货
    public function delBatchById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $batchModel = M("module_order_batch_delivery");
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        $condition['id']=array("eq",$id);
        $data['deleted']=1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result = $batchModel->where($condition)->save($data);
        $orderResult = $orderModel->where("batchId=$id")->setField("batchId",null);
        if($result!==false&&$orderResult!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //新增批量发货
    public function saveBatch($oids,$id=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $batchModel = M("module_order_batch_delivery");
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        $oids = explode(",",$oids);
        $data['cId']=$customerId;
        if($id){
            $batchInfo = $batchModel->where("id=$id")->find();
            $data['orderCount'] = $batchInfo['orderCount']+count($oids);
            $data['updateTime'] = date("Y-m-d H:i:s");
            $batchModel->where("id=$id")->save($data);
        }else{
            $data['deliveryNumber'] = time().$customerId.mt_rand(100,999);
            $data['orderCount'] = count($oids);
            $data['createTime'] = date("Y-m-d H:i:s");
            $data['updateTime'] = date("Y-m-d H:i:s");
            $id = $batchModel->add($data);
        }
        $orderWhere['id']=array("in",$oids);
        $result = $orderModel->where($orderWhere)->setField("batchId",$id);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //根据批量发货id查询订单
    public function getOrderByBatchId($id,$expressNo=NULL,$channelId=null,$serialNumber=NULL,$start=0,$limit=10,$isExport=0){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $orderDetail = M("module_product_order_detail");
        Session::switchCustomer($customerId);
        $condition['od.batchId']=array("eq",$id);
        $expressNo?$condition['od.expressNo']=array("like","%$expressNo%"):"";
        $serialNumber?$condition['detail.serialNumber']=array("like","%$serialNumber%"):"";
        $channelId?$condition['od.fromCustomerId']=array("eq","$channelId"):"";
        if(!$isExport) {
            $orderList = $orderModel->alias("od")
                ->join("wx_module_product_order_detail detail on od.id=detail.oid")
                ->join("wx_customer_user cuser on od.fromCustomerId=cuser.customerId and cuser.agent='business'")
                ->field("od.id")
                ->where($condition)
                ->group("od.id")
                ->limit($start,$limit)
                ->order("od.createTime desc")
                ->select();
            foreach($orderList as $key=>$value){
                $oids[]=$value["id"];
            }
            $oids = implode(",",$oids);
            $arr = $orderModel->alias("od")
                ->join("inner join wx_module_product_order_detail detail on od.id=detail.oid")
                ->join("wx_module_product_order_detail_specification c on detail.id=c.did")
                ->join("wx_customer_user cuser on od.fromCustomerId=cuser.customerId and cuser.agent='business'")
                ->where("od.id in ($oids)")
                ->field("od.id,od.expressNo,od.fullName,detail.name,c.firstSpecificName,c.secSpecificName,
            detail.count,round((detail.isVendorCut/detail.count),2) as isVendorCut,od.status,detail.serialNumber,
            round((detail.ppat/detail.count),2) as ppat,od.ppat as totalPpat,od.createTime,cuser.fullName as userName")
                ->order("od.createTime desc")
                ->select();
            foreach ($arr as $key => $value) {
                $rowspan=1;
                for($i=$key+1;$i<count($arr);$i++){
                    $v = $arr[$i];
                    if($value['id']==$v['id']){
                        $rowspan++;
                    }else{
                        break;
                    }
                }
                $arr[$key]['rowspan'] = $rowspan;
            }
            if ($arr) {
                $count = $orderModel->alias("od")
                    ->join("wx_module_product_order_detail detail on od.id=detail.oid")
                    ->join("wx_customer_user cuser on od.fromCustomerId=cuser.customerId and cuser.agent='business'")
                    ->where($condition)
                    ->group("od.id")
                    ->select();
                $count = count($count);
                Output::instance()->objArray($arr, $count);
            } else {
                Output::instance()->resultCode();
            }
        }else if($isExport==1){
            $arr = $orderModel->alias("od")
                ->join("inner join wx_module_product_order_detail detail ON detail.oid = od.id")
                ->join("wx_module_product_order_detail_specification pSpec ON detail.id = pSpec.did")
                ->where($condition)
                ->order("od.fullName desc,od.createTime desc")
                ->field("od.serialNumber,detail.serialNumber as proSerialNumber,detail.name,pSpec.firstSpecificName,pSpec.secSpecificName,
               round((detail.isVendorCut/detail.count),2) as isVendorCut,detail.customsPrice,detail.count,detail.customsPrice*detail.count as totalCusomsPrice,detail.tariff,
               round((detail.ppat/detail.count),2) as ppat,od.fullName,od.phone,od.expressName,od.expressNo,od.remark,od.address,od.sellerRemark,od.createTime,od.IDName,od.IDNumber")
                ->group("detail.id")
                ->select();
            $data[0] = array(
                'serialNumber'=>'订单号',
                'proSerialNumber'=>'商品条形码',
                'name'=>'商品名称',
                'firstSpecificName'=>'规格1',
                'secSpecificName'=>'规格2',
                'isVendorCut'=>'供应价格',
                'customsPrice'=>'报关单价',
                'count' => '数量',
                'totalCusomsPrice'=>'报关金额',
                'tariff'=>'税率',
                'ppat'=>'行邮税',
                'fullName'=>'买家姓名',
                'phone' => '买家手机电话',
                'express'=>'物流公司',
                'expressNo'=>'物流单号',
                'remark'=>'买家备注',
                'province'=>'省',
                'city'=>'市',
                'area'=>'县',
                'street'=>'地址',
                'address' => '买家收货地址',
                'sellerRemark'=>'卖家备注',
                'createTime'=>'下单时间',
                'IDName'=>"真实姓名",
                'IDNumber'=>'身份证号码',
                'isNum'=>'5,6,7,8,9,10',
                'istitle'=>'1'
            );
            foreach ($arr as $k1 => $v1) {
                $data[$k1+1]['serialNumber']=$v1['serialNumber'];
                $data[$k1+1]['proSerialNumber']=$v1['proSerialNumber'];
                $data[$k1+1]['name']=$v1['name'];
                $data[$k1+1]['firstSpecificName']=$v1['firstSpecificName'];
                $data[$k1+1]['secSpecificName']=$v1['secSpecificName'];
                $data[$k1+1]['isVendorCut']=$v1['isVendorCut'];
                $data[$k1+1]['customsPrice']=$v1['customsPrice'];
                $data[$k1+1]['count']=$v1['count'];
                $data[$k1+1]['totalCusomsPrice']=$v1['totalCusomsPrice'];
                $data[$k1+1]['tariff']=$v1['tariff'];
                $data[$k1+1]['ppat']=$v1['ppat'];
                $data[$k1+1]['fullName'] = $v1['fullName'];
                $data[$k1+1]['phone'] = $v1['phone'];
                $data[$k1+1]['express']='';
                $data[$k1+1]['expressNo']=$v1['expressNo'];
                $data[$k1+1]['remark']=$v1['remark'];
                if($v1['province']){
                    $address['province'] = $v1['province'];
                    $address['city'] = $v1['city'];
                    $address['area'] = $v1['country'];
                    $address['street'] = $v1['address'];
                    $v1['address'] =  $v1['province'].$v1['city'].$v1['country'].$v1['address'];
                }else{
                    $address = R("Product/addressFomate",array($v1['address']));
                }
                $data[$k1+1]['province'] = $address['province'];
                $data[$k1+1]['city'] = $address['city'];
                $data[$k1+1]['area'] = $address['area'];
                $data[$k1+1]['street'] = $address['street'];
                $data[$k1+1]['address'] = $v1['address'];
                $data[$k1+1]['sellerRemark']=$v1['sellerRemark'];
                $data[$k1+1]['createTime']=$v1['createTime'];
                $data[$k1+1]['IDName']=$v1['IDName'];
                $data[$k1+1]['IDNumber']=$v1['IDNumber'];
            }
            Output::instance()->objArrayExcel('订单信息'.date("Y-m-d H:i:s"), '', $data);
        }else if($isExport==2){
            $storeModel = M("");

            $arr = $orderModel->alias("od")
                ->join("inner join wx_module_product_order_detail detail ON detail.oid = od.id")
                ->where($condition)
                ->order("od.fullName desc,od.createTime desc")
                ->field("od.fromCustomerId,od.serialNumber,od.fullName,od.address,od.phone")
                ->group("od.phone")
                ->select();
            $data[0] = array(
                'serialNumber'=>'订单号',
                'name'=>'商品名称',
                'company'=>'单位',
                'count' => '数量',
                'price'=>'单价',
                'weight'=>'重量',
                'skuCode'=>'SKU编码',
                'skuName'=>'SKU名称',
                'clientName'=>'客户名称',
                'remark'=>'备注',
                'fullName'=>'收件人姓名',
                'province'=>'收件人省',
                'city'=>'收件人市',
                'area'=>'收件人区',
                'address' => '收件人地址',
                'zipCode'=>'收件人邮编',
                'tel' => '收件人电话',
                'phone'=>'收件人手机',
                'mailbox'=>'收件人邮箱',
                'shipperName'=>'发件人姓名',
                'shipperProvince'=>'发件人省',
                'shipperCity'=>'发件人市',
                'shipperArea'=>'发件人区',
                'shipperAddress'=>'发件人地址',
                'shipperZipCode'=>'发件人邮编',
                'shipperTel'=>'发件人电话',
                'shipperPhone'=>"发件人手机",
                'shipperZipCode'=>'发件人邮箱',
                'extensionNumber'=>'扩展单号',
                'batchNumber'=>'批次号',
                'paintMarker'=>'大头笔',
                'planeNumber'=>'面单号',
                'payment'=>'代收货款',
                'toPpay'=>'到付款',
                'dotID'=>'网点ID',
                'istitle'=>'1'
            );
            foreach ($arr as $k1 => $v1) {
                $storeInfo = $storeModel->table("wx_".$v1['fromCustomerId']."_module_mall_store")->find();
                $batchInfo = json_decode($storeInfo['json'],true);
                $data[$k1+1]['serialNumber']=$v1['serialNumber'];
                $data[$k1+1]['name']='';
                $data[$k1+1]['company']='';
                $data[$k1+1]['count']='';
                $data[$k1+1]['price']='';
                $data[$k1+1]['weight']='';
                $data[$k1+1]['skuCode']='';
                $data[$k1+1]['skuName']='';
                $data[$k1+1]['clientName']=$batchInfo['clientName'];
                $data[$k1+1]['remark']='';
                $data[$k1+1]['fullName'] = $v1['fullName'];
                if($v1['province']){
                    $address['province'] = $v1['province'];
                    $address['city'] = $v1['city'];
                    $address['area'] = $v1['country'];
                    $address['street'] = $v1['address'];
                    $v1['address'] =  $v1['province'].$v1['city'].$v1['country'].$v1['address'];
                }else{
                    $address = R("Product/addressFomate",array($v1['address']));
                }
                $data[$k1+1]['province'] = $address['province'];
                $data[$k1+1]['city'] = $address['city'];
                $data[$k1+1]['area'] = $address['area'];
                $data[$k1+1]['address'] = $v1['address'];
                $data[$k1+1]['zipCode']='';
                $data[$k1+1]['tel']=$v1['phone'];
                $data[$k1+1]['phone']=$v1['phone'];
                $data[$k1+1]['mailbox']='';
                $data[$k1+1]['shipperName']=$batchInfo['shipperName'];
                $data[$k1+1]['shipperProvince']='';
                $data[$k1+1]['shipperCity']='';
                $data[$k1+1]['shipperArea']='';
                $data[$k1+1]['shipperAddress']=$batchInfo['shipperAddress'];
                $data[$k1+1]['shipperZipCode']='';
                $data[$k1+1]['shipperTel']=$batchInfo['shipperTel'];
                $data[$k1+1]['shipperPhone']=$batchInfo['shipperPhone'];
                $data[$k1+1]['shipperZipCode']='';
                $data[$k1+1]['extensionNumber']='';
                $data[$k1+1]['batchNumber']='';
                $data[$k1+1]['paintMarker']='';
                $data[$k1+1]['planeNumber']='';
                $data[$k1+1]['payment']='';
                $data[$k1+1]['toPpay']='';
                $data[$k1+1]['dotID']='';
            }
            Output::instance()->objArrayExcel('中通订单'.date("Y-m-d H:i:s"), '', $data);
        }else{
            $path = LOCAL_PIC_PATH."bitchDelivery";
            $zipName = LOCAL_PIC_PATH."ID".time().".zip";
            $fileName = LOCAL_PIC_PATH."bitchDelivery/clearance".time().".xls";
//            $path = "E:\\bitchDelivery";
//            $zipName = "E:\\ID".time().".zip";
//            $fileName = "E:\\bitchDelivery\\clearance".time().".xls";
            $arr = $orderModel->alias("od")
                ->join("inner join wx_module_product_order_detail detail ON detail.oid = od.id")
                ->join("wx_module_product_order_detail_specification pSpec ON detail.id = pSpec.did")
                ->where($condition)
                ->order("fullName desc,od.createTime desc")
                ->field("od.expressNo,od.fullName,od.IDNumber,detail.customsPrice,detail.name,detail.count,od.address,od.phone,od.IDSynthetic,
                pSpec.firstSpecificName,pSpec.secSpecificName")
                ->group("detail.id")
                ->select();
            $data[0] = array(
                'temp'=>'序号',
                'expressNo'=>'分单号',
                'fullName'=>'收件人姓名',
                'IDNumber'=>'收件人身份证号码',
                'name'=>'货物名称',
                'count' => '数量',
                'dutyNumber'=>'税号',
                'tariff'=>'税率',
                'pageNumber'=>'件数',
                'weight'=>'重量',
                'customsPrice'=>'单价',
                'ppat'=>'税金',
                'putStatus'=>'险放状态',
                'address' => '地址',
                'phone'=>'收货人电话',
                'isNum'=>'5,10',
                'istitle'=>'1'
            );
            foreach($arr as $k1=>$v1){
                $suffix = pathinfo($v1['IDSynthetic'], PATHINFO_EXTENSION);
                $filName = $path."/".$v1['IDNumber'].".".$suffix;
                self::saveImg($path,$v1['IDSynthetic'],$filName);
                $data[$k1+1]['temp']='';
                $data[$k1+1]['expressNo']=$v1['expressNo'];
                $data[$k1+1]['fullName']=$v1['fullName'];
                $data[$k1+1]['IDNumber']=$v1['IDNumber'];
                $data[$k1+1]['name']=$v1['name'].$v1['firstSpecificName'].$v1['secSpecificName'];
                $data[$k1+1]['count']=$v1['count'];
                $data[$k1+1]['dutyNumber']='';
                $data[$k1+1]['tariff']='';
                $data[$k1+1]['pageNumber']='';
                $data[$k1+1]['weight']='';
                $data[$k1+1]['customsPrice']=$v1['customsPrice'];
                $data[$k1+1]['ppat']='';
                $data[$k1+1]['putStatus']='';
                $data[$k1+1]['address']=$v1['address'];
                $data[$k1+1]['phone']=$v1['phone'];
            }
            Output::instance()->objArrayExcelToPath($fileName, '', $data);
            self::getIDZip($path,$zipName);
        }
    }
    //从批量发货中删除订单
    public function delOrderFromBatch($oid,$batchId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $batchModel = M("module_order_batch_delivery");
        $orderModel = M("module_product_order");
        Session::switchCustomer($customerId);
        $orderResult = $orderModel->where("id=$oid")->setField("batchId",NULL);
        if($orderResult!==false){
            $batchResult = $batchModel->where("id=$batchId")->setDec("orderCount");
            if($batchResult!==false){
                Output::instance()->resultCode();
                return;
            }
        }
        Output::instance()->resultCode(code_sql_error);
    }
    //批量发货状态列表
    public function batchStatusList($id,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $batchStatus = M("module_order_batch_track");
        Session::switchCustomer($customerId);
        $condition['batchId']=array("eq",$id);
        $condition['deleted']=array("eq",0);
        $arr = $batchStatus->where($condition)->limit($start,$limit)->order("createTime desc")->select();
        if($arr){
            $count = $batchStatus->where($condition)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }

    }
    public function addBatchStatus($id,$description,$createTime){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $batchStatus = M("module_order_batch_track");
        Session::switchCustomer($customerId);
        $data['batchId']=$id;
        $data['description']=$description;
        $data['createTime']=$createTime;
        $data['deleted']=0;
        $result = $batchStatus->add($data);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //删除状态
    public function delBtachStatusById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $batchStatus = M("module_order_batch_track");
        Session::switchCustomer($customerId);
        $result = $batchStatus->where("id=$id")->setField("deleted",1);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //默认批量发货状态列表
    public function defaultStatusList(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $defaultStatus = M("module_batch_track");
        Session::switchCustomer($customerId);
        $condition['deleted']=array("eq",0);
        $condition['cId']=array("eq",$customerId);
        $arr =$defaultStatus->where($condition)->order("createTime desc")->select();
        $result['list']=$arr;
        Output::instance()->object($result);

    }
    //删除默认状态
    public function delStatusById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $defaultStatus = M("module_batch_track");
        Session::switchCustomer($customerId);
        $result = $defaultStatus->where("id=$id")->setField("deleted",1);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //添加默认状态
    public function addDefaultStatus($description){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $defaultStatus = M("module_batch_track");
        Session::switchCustomer($customerId);
        $data['cId']=$customerId;
        $data['description']=$description;
        $data['deleted']=0;
        $data['createTime']=date("Y-m-d H:i:s");
        $result = $defaultStatus->add($data);
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }

    private function getIDZip($path,$filename){
        $zip = new ZipArchive(); // 使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if($zip->open($filename, ZIPARCHIVE::CREATE)=== TRUE){
            self::addFileToZip($path, $zip); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
            $zip->close(); //关闭处理的zip文件
        }
        self::removeDir($path);
        header('Content-type: application/force-download');
        header('Content-Disposition: attachment; filename='.basename($filename));
        @readfile($filename);
        unlink($filename);
    }
    private function addFileToZip($path,$zip){
        $handler=opendir($path); //打开当前文件夹由$path指定。
        while(($filename=readdir($handler))!==false){
            if($filename != "." && $filename != ".."){//文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if(is_dir($path."/".$filename)){// 如果读取的某个对象是文件夹，则递归
                    addFileToZip($path."/".$filename, $zip);
                }else{ //将文件加入zip对象
                    $zip->addFile($path."/".$filename,$filename);
                }
            }
        }
        @closedir($path);
    }
    private function saveImg($path,$filPath,$filName){
        if(!file_exists($path)){
            mkdir ($path);
        }
        $ch = curl_init ($filPath);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
        $img = curl_exec ($ch);
        curl_close ($ch);
        $fp = fopen($filName,'w');
        fwrite($fp, $img);
        fclose($fp);
    }
    private function removeDir($dirName)
    {
        if(! is_dir($dirName))
        {
            return false;
        }
        $handle = @opendir($dirName);
        while(($file = @readdir($handle)) !== false)
        {
            if($file != '.' && $file != '..')
            {
                $dir = $dirName . '/' . $file;
                is_dir($dir) ? self::removeDir($dir) : @unlink($dir);
            }
        }
        closedir($handle);

        return rmdir($dirName) ;
    }

}